package persistent.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

import basic.HibBaseDAO;
import basic.HibernateSessionFactory;
import model.TCloudParentClass;
import model.TCloudParentStudent;
import model.TCloudUser;
import model.TParentInfo;
import model.VCloudParentClass;
import model.VCloudParentStudent;
import persistent.dao.ParentInfoDAO;
import util.toolkit.Constant;
import util.toolkit.LogUtil;

/**
 * 家长业务类接口的实现
 * @author djf
 * @since 2018/10/2
 */
public class ParentInfoImpl implements ParentInfoDAO {
	
	private HibBaseDAO dao=null;
	private static final Log log = LogFactory.getLog(ParentInfoImpl.class);

	public ParentInfoImpl() {
		dao=new HibBaseDAO();
	}
	
	/**
	 * 添加一个学生家长
	 * @param vps 家长学生对应关系列表
	 * @param roleid 家长角色编号
	 * @return 成功返回主键，失败返回0
	 * @since 2018-12-04 16:08
	 */
	@Override
	public boolean addParent(List<VCloudParentStudent> vps, int roleid) {
		
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		
		try{
			TParentInfo parent = new TParentInfo();
			parent.setRealName(vps.get(0).getParRealName());
			parent.setSex(vps.get(0).getParSex());
			parent.setPhone(vps.get(0).getPhone());
			parent.setSchoolid(vps.get(0).getSchoolid());
			parent.setRoleid(roleid);			
			Serializable key = session.save(parent);// 先保存用户信息表
			int row = ((Integer) key).intValue();// 得到自动编号
			if(row > 0){
				for (int i = 0; i < vps.size(); i++) {				
					TCloudParentStudent tps = new TCloudParentStudent();
					tps.setParentid(row);
					tps.setRelation(vps.get(i).getRelation());
					tps.setSchoolid(vps.get(i).getSchoolid());
					tps.setStuid(vps.get(i).getStuid());
					session.save(tps);			
				}
			}
			else {
				if(tx != null) tx.rollback();
				session.close(); //关闭连接
				return false;
			}
			tx.commit();
			session.close();//关闭连接
			return true;
		} catch (Exception e) {
			if(tx != null) tx.rollback();
			session.close(); //关闭连接
			log.error("persistent.impl包ParentInfoImpl类addParent(List<VCloudParentStudent> vps, int roleid)方法调用错误：");
			log.error(LogUtil.getMsg(e));
			System.out.println("persistent.impl包ParentInfoImpl类addParent(List<VCloudParentStudent> vps, int roleid)方法调用错误：");
			e.printStackTrace();
		}
		return false;		
	}

	/**
	 * 修改一个家长信息
	 * @param parent 家长信息对象
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean updateParent(TParentInfo parent) {
		TParentInfo parent2=(TParentInfo)dao.findById(TParentInfo.class, parent.getParinfoid());
		parent2.setUserName(parent.getUserName());
		parent2.setRealName(parent.getRealName());
		parent2.setSex(parent.getSex());
		parent2.setBirthday(parent.getBirthday());
		parent2.setEmail(parent.getEmail());
		parent2.setAddress(parent.getAddress());
		parent2.setPhone(parent.getPhone());
		parent2.setTell(parent.getTell());
		parent2.setWorkTel(parent.getWorkTel());
		parent2.setWorkUnit(parent.getWorkUnit());
		parent2.setEducation(parent.getEducation());
		parent2.setActiveState(parent.getActiveState());
		parent2.setRoleid(parent.getRoleid());
		parent2.setWorkType(parent.getWorkType());
		parent2.setSchoolid(parent.getSchoolid());
		parent2.setUserid(parent.getUserid());
		return dao.update(parent2);
	}

	/**
	 * 根据一个用户名得到一个家长
	 * @param userName 用户名
	 * @return 成功返回TParentInfo家长用户对象，失败返回null
	 */
	@Override
	public TParentInfo getTParentInfo(int parinfoid) {
		return (TParentInfo)dao.findById(TParentInfo.class, parinfoid);
	}

	/**
	 * 根据查询条件得到家长列表
	 * @param strwhere 查询条件
	 * @return 成功返回TParentInfo对象的家长信息列表，失败返回null
	 */
	@Override
	public List<TParentInfo> getParentList(String strwhere) {
		String hql="from TParentInfo "+strwhere;
		return dao.select(hql);
	}

	/**
	 * 根据查询条件得到一个分页的家长信息列表
	 * @param strwhere 查询条件
	 * @param currentPage 当前页
	 * @param pageSize 每页数
	 * @return 成功返回TParentInfo对象的家长信息列表，失败返回null
	 */
	@Override
	public List<TParentInfo> getParentListByPage(String strwhere,
			int currentPage, int pageSize) {
		String hql="from TParentInfo "+strwhere;
		return dao.selectByPage(hql, currentPage, pageSize);
	}
	
	/**
	 * 根据条件查询家长信息列表
	 * @param strwhere 查询条件
	 * @return 成功返回VCloudParentClass列表，失败返回null
	 */
	/*@Override
	public List<VCloudParentClass> getParentByClass(String strwhere) {
		String hql="from VCloudParentClass "+strwhere;
		return dao.select(hql);
	}*/
	
	/**
	 * 根据班级查询家长信息列表
	 * @param strwhere 查询条件
	 * @return 成功返回VCloudParentClass列表，失败返回null
	 */
	/*@Override
	public List<VCloudParentClass> getParentByClass(String strwhere,int currentPage, int pageSize) {
		String hql="from VCloudParentClass "+strwhere;
		return dao.selectByPage(hql, currentPage, pageSize);
	}*/
	
	/**
	 * 根据条件查询出家长学生对应信息
	 * @param strwhere 查询条件 
	 * @return 成功返回VCloudParentStudent，失败返回null
	 */
	@Override
	public List<VCloudParentStudent> getParentStudent(String strwhere) {
		String hql="from VCloudParentStudent "+strwhere;
		return dao.select(hql);
	}
	
	/**
	 * 根据插叙条件得到学生家长控制类
	 * @param strwhere 查询条件 
	 * @param currentPage 当前页
	 * @param pageSize 每页数
	 * @return 成功返回VCloudParentStudent，失败返回null
	 */
	@Override
	public List<VCloudParentStudent> getParentStudent(String strwhere,
			int currentPage, int pageSize) {
		String hql="from VCloudParentStudent "+strwhere;
		return dao.selectByPage(hql, currentPage, pageSize);
	}
	
	/**
	 * 根据条件查询出接收家长信息(发送事项接收家长)
	 * @param strwhere 查询条件 
	 * @return 成功返回VCloudParentStudent，失败返回null
	 */
	/*@Override
	public List<VCloudReceiveParent> getReceiveParent(String strwhere) {
		String hql="from VCloudReceiveParent "+strwhere;
		return dao.select(hql);
	}*/
	
	/**
	 * 批量导入学生家长关系信息
	 * @param list 关系信息列表
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public List<VCloudParentStudent> batchImport(List<VCloudParentStudent> psList, int parroleid) {
		
		Session session1 = HibernateSessionFactory.getSession();		
		Transaction tx1 = null; 
		tx1 = session1.beginTransaction();
		
		List<VCloudParentStudent> failList = new ArrayList<VCloudParentStudent>();
		for (int i = 0; i < psList.size(); i++) {
			try {		
				//得到自动编号
				int userid = 0;
				int parid = 0;
				try {
					TParentInfo parentInfo = new TParentInfo();
					parentInfo.setRealName(psList.get(i).getParRealName());
					parentInfo.setSex(psList.get(i).getParSex());
					parentInfo.setPhone(psList.get(i).getPhone());
					parentInfo.setSchoolid(psList.get(i).getSchoolid());
					parentInfo.setRoleid(parroleid);
					//先保存家长信息
					Serializable userKey = session1.save(parentInfo);
					userid = ((Integer)userKey).intValue();
				} catch (ConstraintViolationException e) {
					String hql = "from VCloudParentStudent where phone = ?";
					Object[] para = { psList.get(i).getPhone() };
					List<VCloudParentStudent> paList = dao.select(hql, para);
					if (paList.get(0).getParRealName().equals(psList.get(i).getParRealName())) {
						parid = paList.get(0).getParentid();
					}
					else {
						failList.add(psList.get(i));
					}
				}
				TCloudParentStudent tps = new TCloudParentStudent();
				if (parid == 0) {
					tps.setParentid(userid);
				}
				else {
					tps.setParentid(parid);
				}
				tps.setRelation(psList.get(i).getRelation());
				tps.setSchoolid(psList.get(i).getSchoolid());
				tps.setStuid(psList.get(i).getStuid());
				session1.save(tps);	
			} catch (Exception e) {
				failList.add(psList.get(i));
				log.error("CloudParentStudentImpl类batchImport(List<VCloudParentStudent> psList)方法调用错误：");
				log.error(LogUtil.getMsg(e));
				System.out.println("CloudParentStudentImpl类batchImport(List<VCloudParentStudent> psList)方法调用错误：");
				e.printStackTrace();				
			}		
		}
		if (tx1 != null && failList.size() == 0) {
			tx1.commit();
			session1.close(); // 关闭连接
		} else if (tx1 != null && failList.size() > 0) {
			tx1.rollback();
			session1.close(); // 关闭连接
		}
		return failList;
	}

	/**
	 * 激活家长账号
	 * @param phone 手机号
	 * @param userName 用户名
	 * @param pwd 密码
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean parActivationaCcount(String phone, String userName,
			String pwd) {	
		String hql = "from TParentInfo where phone = ?";
		Object[] para = {phone};
		List<TParentInfo> parList = dao.select(hql, para);
		TCloudUser user = new TCloudUser();
		if (parList != null && parList.size() > 0) {
			user = (TCloudUser) dao.findById(TCloudUser.class, parList.get(0).getUserid());
			user.setPwd(pwd);
			user.setUserName(userName);
			user.setStatus(Constant.ENABLE);
			boolean row = dao.update(user);
			if (row) {
				return true;
			}
			else {
				return false;
			}
		}
		return false;	
	}

	/**
	 * 删除一个家长信息
	 * @param parid 家长id
	 * @return 成功返回true，失败返回false
	 * @since 2018-11-24 11:45
	 * @since 2019-01-12 11:02 徐震霖改
	 */
	@Override
	public boolean deleteParent(int parid) {
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		try {
			TParentInfo paInfo = (TParentInfo) dao.findById(TParentInfo.class, parid);
			String hql = "from TCloudUser where phone = ?";
			Object[] para = { paInfo.getPhone() };
			List<TCloudUser> userlist = dao.select(hql, para);	
			
			if(userlist != null && userlist.size() > 0){
				if (tx != null) tx.rollback();
				session.close(); // 关闭连接
				return false;
			}
			else {
				String hql1 = "from TCloudParentStudent where parentid = ?";
				Object[] para1 = { paInfo.getParinfoid() };
				List<TCloudParentStudent> parstulist = dao.select(hql1, para1);				
				for (TCloudParentStudent tCloudParentStu : parstulist) {
					session.delete(tCloudParentStu);
				}
			}		    
			session.delete(paInfo);
			tx.commit();// 统一提交
			session.close();// 关闭连接
			return true;
		} catch (Exception e) {
			if (tx != null) tx.rollback();
			session.close(); // 关闭连接
			log.error("persistent.impl包ParentInfoImpl类deleteParent(int parid)方法调用错误：");
			log.error(LogUtil.getMsg(e));
			System.out.println("persistent.impl包ParentInfoImpl类deleteParent(int parid)方法调用错误：");
			e.printStackTrace();
		}
		return false;
	}
}
